import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../services/audio_player_service.dart';
import '../../services/file_service.dart';
import '../../services/theme_service.dart';
import 'preview_utils.dart';
import 'theme_config_panel.dart';

/// 创建一个散列函数来创建唯一的播放器ID
String _getAudioPlayerId(String? url, String? fileName) {
  return '${url ?? 'unknown'}_${fileName ?? 'unnamed'}';
}

/// 增强型音频预览组件
/// 使用Riverpod状态管理，支持音频大小不限制，包含缓冲区间计算和自动恢复机制
class EnhancedAudioPreview extends ConsumerStatefulWidget {
  final String? previewUrl;
  final String? fileName;
  final String? extension;
  final String? mimeType;
  final int? fileSize;
  final Function(bool)? onReloadRequest;

  const EnhancedAudioPreview({
    Key? key,
    required this.previewUrl,
    this.fileName,
    this.extension,
    this.mimeType,
    this.fileSize,
    this.onReloadRequest,
  }) : super(key: key);

  @override
  ConsumerState<EnhancedAudioPreview> createState() =>
      _EnhancedAudioPreviewState();
}

class _EnhancedAudioPreviewState extends ConsumerState<EnhancedAudioPreview>
    with WidgetsBindingObserver {
  bool _isInitialized = false;
  bool _isHighQualityMode = false;
  bool _isLoading = false; // 添加加载状态标记
  bool _hasActivePlayer = false; // 跟踪播放器是否活跃
  int _errorRetryCount = 0; // 错误重试计数
  final Map<String, String> _headers = {
    'User-Agent':
        PreviewUtils.isAndroid
            ? 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36'
            : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': '*/*',
    'Accept-Encoding': 'identity;q=1, *;q=0',
    'Range': 'bytes=0-',
  };

  // 当前音频的唯一ID
  String? _currentAudioId;

  // 创建渐变色主题
  LinearGradient _getThemeGradient(BuildContext context) {
    final themeConfig = ref.watch(appThemeConfigProvider);
    return LinearGradient(
      colors: themeConfig.gradientColors,
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    );
  }

  // 获取浅色主题色
  Color _getLightThemeColor(BuildContext context) {
    final themeConfig = ref.watch(appThemeConfigProvider);
    return themeConfig.primaryColor.withOpacity(0.7);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadAudio();
  }

  @override
  void didUpdateWidget(EnhancedAudioPreview oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.previewUrl != widget.previewUrl && !_isLoading) {
      _loadAudio();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    // 修复：直接在dispose中安全释放资源，避免调用可能使用ref的方法
    if (_hasActivePlayer) {
      try {
        // 使用安全暂停方法，不使用ref进行完整释放
        final audioNotifier = ref.read(audioPlayerProvider.notifier);
        audioNotifier.safetyPause(); // 使用安全暂停方法
        _hasActivePlayer = false;
      } catch (e) {
        print('安全释放播放器资源时出错: $e');
        // 错误可以忽略，因为组件正在被销毁
      }
    }

    super.dispose();
  }

  // 监听应用生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 当应用进入后台时，暂停并释放资源以避免MediaCodec错误
    if (state == AppLifecycleState.paused) {
      try {
        if (!mounted) return; // 添加mounted检查

        final audioState = ref.read(audioPlayerProvider);
        if (audioState.isPlaying || audioState.isBuffering) {
          print('应用进入后台，暂停并安全释放音频播放器');
          final audioNotifier = ref.read(audioPlayerProvider.notifier);
          audioNotifier.safetyPause(); // 使用安全暂停方法
        }
      } catch (e) {
        print('应用生命周期处理时出错: $e');
        // 忽略错误
      }
    } else if (state == AppLifecycleState.resumed) {
      try {
        if (!mounted) return; // 添加mounted检查

        // 应用回到前台，如果播放器状态异常，重新加载
        final audioState = ref.read(audioPlayerProvider);
        if (_hasActivePlayer && audioState.hasError) {
          print('应用回到前台，检测到错误状态，重新加载音频');
          _loadAudio();
        }
      } catch (e) {
        print('应用恢复前台时出错: $e');
        // 忽略错误，可能需要重新加载音频
        if (mounted) {
          // 添加mounted检查
          Future.delayed(Duration(milliseconds: 500), () {
            if (mounted) {
              // 再次检查延迟后的mounted状态
              _loadAudio();
            }
          });
        }
      }
    }
  }

  /// 释放音频播放器资源
  void _releaseAudioPlayer() {
    if (!mounted) return; // 添加mounted检查

    if (_hasActivePlayer) {
      try {
        final audioNotifier = ref.read(audioPlayerProvider.notifier);
        audioNotifier.release();
        _hasActivePlayer = false;
      } catch (e) {
        print('释放播放器资源时出错: $e');
        // 错误可以忽略，因为组件可能正在被销毁
        _hasActivePlayer = false;
      }
    }
  }

  /// 加载音频
  Future<void> _loadAudio() async {
    if (widget.previewUrl == null || _isLoading || !mounted)
      return; // 添加mounted检查

    try {
      _isLoading = true; // 设置加载状态
      print('尝试加载音频: ${widget.previewUrl}');

      // 创建唯一ID以确保不同音频有独立状态
      _currentAudioId = _getAudioPlayerId(widget.previewUrl, widget.fileName);
      print('音频ID: $_currentAudioId');

      // 获取Notifier
      final audioNotifier = ref.read(audioPlayerProvider.notifier);

      // 标记为正在初始化
      if (!_isInitialized && mounted) {
        // 添加mounted检查
        setState(() {
          _isInitialized = true;
        });
      }

      // 如果是大文件，显示提示但不阻止加载
      if (!_isHighQualityMode &&
          widget.fileSize != null &&
          widget.fileSize! > 100 * 1024 * 1024 &&
          mounted) {
        // 添加mounted检查
        // 只在第一次加载时显示提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '音频文件较大 (${FileService.formatFileSize(widget.fileSize!)}), 已优化加载方式\n'
              '跳转到未缓冲区域时将优先加载该区域',
            ),
            duration: const Duration(seconds: 5),
            action: SnackBarAction(
              label: '高质量模式',
              onPressed: () {
                if (mounted) {
                  // 添加mounted检查
                  setState(() {
                    _isHighQualityMode = true;
                  });
                  _loadAudio(); // 重新加载
                }
              },
            ),
            backgroundColor: _getLightThemeColor(context).withOpacity(0.8),
          ),
        );
      }

      // 为减少初始缓冲问题，使用延迟加载
      await Future.delayed(const Duration(milliseconds: 100));

      if (!mounted) return; // 延迟后检查mounted状态

      // 加载音频前先释放之前的实例
      await audioNotifier.release();

      // 加载音频
      await audioNotifier.loadUrl(widget.previewUrl!, headers: _headers);
      _hasActivePlayer = true;
      _errorRetryCount = 0; // 重置错误计数
    } catch (e) {
      print('音频加载错误: $e');
      if (_isInitialized && mounted) {
        // 添加mounted检查
        setState(() {
          _isInitialized = false;
        });
      }
    } finally {
      if (mounted) {
        // 添加mounted检查
        _isLoading = false; // 重置加载状态
      }
    }
  }

  /// 处理播放器错误
  void _handlePlayerError(String error) {
    if (!mounted) return; // 添加mounted检查

    _errorRetryCount++;

    // 如果错误包含特定关键词，或者重试次数过多，重置播放器
    if (error.contains('缓冲卡住') ||
        error.contains('解码器错误') ||
        error.toLowerCase().contains('mediacodec') ||
        _errorRetryCount > 3) {
      print('检测到严重错误或多次重试失败，完全重置播放器');
      _releaseAudioPlayer();
      if (mounted) {
        // 添加mounted检查
        Future.delayed(const Duration(milliseconds: 500), () {
          if (mounted) {
            // 再次检查延迟后的mounted状态
            _loadAudio();
          }
        });
      }
    }
  }

  /// 格式化时间
  String _formatDuration(Duration duration) {
    return PreviewUtils.formatDuration(duration);
  }

  @override
  Widget build(BuildContext context) {
    // 监视特定audioId的状态，确保不同音频有独立状态
    final audioState = ref.watch(audioPlayerProvider);
    final themeConfig = ref.watch(appThemeConfigProvider);

    // 验证当前状态是否属于此音频
    if (audioState.currentUrl != null &&
        audioState.currentUrl != widget.previewUrl) {
      // 如果状态不匹配，重新加载当前音频
      if (!_isLoading) {
        Future.microtask(() => _loadAudio());
      }
      // 展示加载界面
      return _buildLoadingView(message: "准备加载新音频...");
    }

    // 处理可恢复的错误 - 如果是缓冲/加载错误，不显示错误页面，只显示提示
    if (audioState.hasError && !audioState.error!.contains('加载音频失败')) {
      // 处理播放器错误
      _handlePlayerError(audioState.error!);

      // 如果是尝试恢复的错误，显示为恢复中状态
      if (audioState.error!.contains('尝试恢复播放')) {
        return _buildLoadingView(message: audioState.error!);
      }
    }

    // 严重错误处理
    if (audioState.hasError && audioState.error!.contains('加载音频失败')) {
      return _buildErrorView(audioState.error!);
    }

    // 加载中状态
    if (audioState.isLoading && !_isInitialized) {
      return _buildLoadingView();
    }

    // 播放器界面
    return _buildAudioPlayer(audioState);
  }

  /// 构建错误视图
  Widget _buildErrorView(String error) {
    final themeGradient = _getThemeGradient(context);
    final themeColor = _getLightThemeColor(context);

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ShaderMask(
            shaderCallback: (bounds) => themeGradient.createShader(bounds),
            child: Icon(Icons.audio_file, size: 80, color: Colors.white),
          ),
          const SizedBox(height: 24),

          // 文件名
          Text(
            widget.fileName ?? '未知音频',
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 12),

          // 文件信息
          if (widget.extension != null || widget.fileSize != null)
            Text(
              '${widget.extension ?? ""} · ${widget.fileSize != null ? FileService.formatFileSize(widget.fileSize!) : "未知大小"}',
              style: const TextStyle(color: Colors.grey),
            ),
          const SizedBox(height: 16),

          // 错误信息
          Container(
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.symmetric(horizontal: 24),
            decoration: BoxDecoration(
              color: Colors.red[50],
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.red[100]!),
            ),
            child: Text(
              error,
              style: TextStyle(color: Colors.red[800]),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 24),

          // 下载和刷新按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                decoration: BoxDecoration(
                  gradient: themeGradient,
                  borderRadius: BorderRadius.circular(24),
                ),
                child: ElevatedButton.icon(
                  onPressed: () async {
                    if (widget.previewUrl != null) {
                      final url = Uri.parse(widget.previewUrl!);
                      if (await canLaunchUrl(url)) {
                        await launchUrl(
                          url,
                          mode: LaunchMode.externalApplication,
                        );
                      }
                    }
                  },
                  icon: const Icon(Icons.download, color: Colors.white),
                  label: const Text(
                    '下载音频',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    shadowColor: Colors.transparent,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 12,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 16),

              // 重试按钮
              TextButton(
                onPressed: () {
                  if (widget.onReloadRequest != null) {
                    widget.onReloadRequest!(false);
                  } else {
                    _loadAudio();
                  }
                },
                child: ShaderMask(
                  shaderCallback:
                      (bounds) => themeGradient.createShader(bounds),
                  child: const Text(
                    '重试加载',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建加载视图
  Widget _buildLoadingView({String? message}) {
    final themeGradient = _getThemeGradient(context);

    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ShaderMask(
            shaderCallback: (bounds) => themeGradient.createShader(bounds),
            child: const CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          ),
          const SizedBox(height: 16),
          ShaderMask(
            shaderCallback: (bounds) => themeGradient.createShader(bounds),
            child: Text(
              message ?? '音频加载中...',
              style: const TextStyle(color: Colors.white),
            ),
          ),
          if (message != null && message.contains('尝试恢复播放'))
            Padding(
              padding: const EdgeInsets.only(top: 16.0),
              child: Container(
                decoration: BoxDecoration(
                  gradient: themeGradient,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: TextButton.icon(
                  icon: const Icon(Icons.refresh, color: Colors.white),
                  label: const Text(
                    '重新加载',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: TextButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 8,
                    ),
                  ),
                  onPressed: _loadAudio,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建音频播放器视图
  Widget _buildAudioPlayer(AudioPlayerState audioState) {
    final audioNotifier = ref.read(audioPlayerProvider.notifier);
    final isAndroid = defaultTargetPlatform == TargetPlatform.android;
    final themeColor = _getLightThemeColor(context);
    final themeGradient = _getThemeGradient(context);
    final themeConfig = ref.watch(appThemeConfigProvider);

    return Stack(
      children: [
        // 背景图片（如果有）
        if (themeConfig.themeType == AppThemeType.custom &&
            themeConfig.backgroundImagePath != null)
          Positioned.fill(
            child: Opacity(
              opacity: themeConfig.backgroundOpacity,
              child: Image.file(
                File(themeConfig.backgroundImagePath!),
                fit: BoxFit.cover,
              ),
            ),
          ),

        // 主内容
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 顶部添加空间，使整体往下挪
                const SizedBox(height: 40),

                // 音频图标 - 使用渐变装饰
                ShaderMask(
                  shaderCallback:
                      (bounds) => themeGradient.createShader(bounds),
                  child: Icon(Icons.audio_file, size: 80, color: Colors.white),
                ),
                const SizedBox(height: 24),

                // 文件名
                Text(
                  widget.fileName ?? '未知音频',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color:
                        themeConfig.isDarkMode
                            ? Colors.white
                            : Theme.of(context).textTheme.titleLarge?.color,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),

                // 文件类型和大小
                Text(
                  '${widget.mimeType ?? "音频文件"} · ${widget.fileSize != null ? FileService.formatFileSize(widget.fileSize!) : "未知大小"}',
                  style: TextStyle(
                    color:
                        themeConfig.isDarkMode
                            ? Colors.white70
                            : Theme.of(
                              context,
                            ).textTheme.bodyMedium?.color?.withOpacity(0.7),
                  ),
                ),

                // 高质量模式标志
                if (_isHighQualityMode)
                  Container(
                    decoration: BoxDecoration(
                      gradient: themeGradient,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.high_quality,
                            size: 16,
                            color: Colors.white,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            '高质量模式',
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ],
                      ),
                    ),
                  ),

                // Android平台显示特殊使用说明
                if (isAndroid &&
                    widget.fileSize != null &&
                    widget.fileSize! > 50 * 1024 * 1024)
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Card(
                      color: themeColor.withOpacity(0.05),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                ShaderMask(
                                  shaderCallback:
                                      (bounds) =>
                                          themeGradient.createShader(bounds),
                                  child: Icon(
                                    Icons.info_outline,
                                    size: 16,
                                    color: Colors.white,
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    '安卓提示：大文件时，播放前等待缓冲完成',
                                    style: TextStyle(
                                      fontSize: 12,
                                      foreground:
                                          Paint()
                                            ..shader = themeGradient
                                                .createShader(
                                                  const Rect.fromLTWH(
                                                    0,
                                                    0,
                                                    200,
                                                    20,
                                                  ),
                                                ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                const SizedBox(height: 40),

                // 缓冲状态提示
                Container(
                  margin: const EdgeInsets.only(bottom: 4),
                  height: 16,
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 使用固定宽度容器显示缓冲百分比，即使没有值也保持空间占位
                      Container(
                        width: 80, // 固定宽度防止布局跳动
                        alignment: Alignment.center,
                        child: AnimatedOpacity(
                          opacity: audioState.loadingProgress > 0 ? 1.0 : 0.0,
                          duration: const Duration(milliseconds: 300),
                          child: Text(
                            '已缓冲: ${(audioState.loadingProgress * 100).toStringAsFixed(0)}%',
                            style: TextStyle(
                              fontSize: 10,
                              foreground:
                                  Paint()
                                    ..shader = themeGradient.createShader(
                                      const Rect.fromLTWH(0, 0, 80, 10),
                                    ),
                            ),
                          ),
                        ),
                      ),
                      // 始终保持缓冲指示器的占位，通过透明度控制显示
                      Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: SizedBox(
                          width: 10,
                          height: 10,
                          child: AnimatedOpacity(
                            opacity: audioState.isBuffering ? 1.0 : 0.0,
                            duration: const Duration(milliseconds: 300),
                            child: ShaderMask(
                              shaderCallback:
                                  (bounds) =>
                                      themeGradient.createShader(bounds),
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                // 进度条 - 确保值永远不超过范围
                if (audioState.duration.inSeconds > 0)
                  Column(
                    children: [
                      // 整合播放进度和缓冲进度
                      SizedBox(
                        height: 20, // 容纳滑块的固定高度
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              // 缓冲进度条 - 放在底层
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 11,
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(1.0),
                                  child: SizedBox(
                                    height: 2,
                                    child: Stack(
                                      alignment: Alignment.centerLeft,
                                      children: [
                                        // 总进度条背景（始终显示）
                                        Container(
                                          height: 2,
                                          decoration: BoxDecoration(
                                            color: themeColor.withOpacity(0.1),
                                            borderRadius: BorderRadius.circular(
                                              1.0,
                                            ),
                                          ),
                                        ),
                                        // 缓冲进度条（从左往右）- 使用渐变
                                        FractionallySizedBox(
                                          widthFactor: audioState
                                              .loadingProgress
                                              .clamp(0.0, 1.0),
                                          alignment: Alignment.centerLeft,
                                          child: Container(
                                            height: 2,
                                            decoration: BoxDecoration(
                                              gradient:
                                                  audioState.isBuffering
                                                      ? themeGradient
                                                      : LinearGradient(
                                                        colors: [
                                                          themeColor
                                                              .withOpacity(0.3),
                                                          themeColor
                                                              .withOpacity(0.4),
                                                        ],
                                                        begin:
                                                            Alignment
                                                                .centerLeft,
                                                        end:
                                                            Alignment
                                                                .centerRight,
                                                      ),
                                              borderRadius:
                                                  BorderRadius.circular(1.0),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),

                              // 播放进度滑块 - 透明轨道，显示在顶层
                              SliderTheme(
                                data: SliderThemeData(
                                  trackHeight: 2,
                                  activeTrackColor: themeColor,
                                  inactiveTrackColor: Colors.transparent,
                                  thumbColor: themeColor,
                                  thumbShape: const RoundSliderThumbShape(
                                    enabledThumbRadius: 6,
                                    elevation: 2,
                                  ),
                                  overlayShape: const RoundSliderOverlayShape(
                                    overlayRadius: 12,
                                  ),
                                  overlayColor: themeColor.withOpacity(0.1),
                                ),
                                child: Slider(
                                  value: PreviewUtils.clamp(
                                    audioState.position.inSeconds.toDouble(),
                                    0,
                                    audioState.duration.inSeconds.toDouble(),
                                  ),
                                  max: audioState.duration.inSeconds.toDouble(),
                                  min: 0,
                                  onChanged: (value) {
                                    // 创建目标位置对象
                                    final targetPosition = Duration(
                                      seconds: value.toInt(),
                                    );

                                    // 检查是否跳转到已缓冲区域
                                    final isBuffered = audioState
                                        .isPositionBuffered(targetPosition);
                                    print(
                                      '进度条拖动，目标位置: $targetPosition, 是否已缓冲: $isBuffered',
                                    );

                                    // 检查是否是大文件或FLAC格式
                                    final isLargeFile =
                                        widget.fileSize != null &&
                                        widget.fileSize! > 20 * 1024 * 1024;
                                    final isFlacFormat =
                                        widget.mimeType?.toLowerCase().contains(
                                              'flac',
                                            ) ==
                                            true ||
                                        widget.extension?.toLowerCase() ==
                                            'flac';
                                    final needsSpecialHandling =
                                        isAndroid &&
                                        (isLargeFile || isFlacFormat);

                                    if (isBuffered && !needsSpecialHandling) {
                                      // 如果已缓冲且不需要特殊处理，直接跳转
                                      audioNotifier.seek(targetPosition);
                                    } else {
                                      // 对于需要特殊处理的情况，使用更安全的跳转方式
                                      // 先暂停播放
                                      final wasPlaying = audioState.isPlaying;
                                      if (wasPlaying) {
                                        audioNotifier.pause();
                                      }

                                      // 给系统足够时间处理暂停操作
                                      Future.delayed(
                                        const Duration(milliseconds: 500),
                                        () {
                                          // 使用seek方法但增加安全措施
                                          audioNotifier.seek(targetPosition);

                                          // 如果之前是播放状态，恢复播放，但给予足够的缓冲时间
                                          if (wasPlaying) {
                                            Future.delayed(
                                              const Duration(milliseconds: 800),
                                              () {
                                                if (mounted) {
                                                  audioNotifier.play();
                                                }
                                              },
                                            );
                                          }
                                        },
                                      );
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                else
                  SizedBox(
                    height: 20,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: SliderTheme(
                        data: SliderThemeData(
                          trackHeight: 2,
                          activeTrackColor: themeColor.withOpacity(0.3),
                          inactiveTrackColor: themeColor.withOpacity(0.1),
                          thumbColor: themeColor.withOpacity(0.5),
                          thumbShape: const RoundSliderThumbShape(
                            enabledThumbRadius: 6,
                            elevation: 2,
                          ),
                        ),
                        child: Slider(
                          value: 0,
                          max: 1,
                          min: 0,
                          onChanged: null,
                        ),
                      ),
                    ),
                  ),

                // 时间显示
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _formatDuration(audioState.position),
                        style: TextStyle(
                          foreground:
                              Paint()
                                ..shader = themeGradient.createShader(
                                  const Rect.fromLTWH(0, 0, 50, 20),
                                ),
                        ),
                      ),
                      Text(
                        _formatDuration(audioState.duration),
                        style: TextStyle(
                          foreground:
                              Paint()
                                ..shader = themeGradient.createShader(
                                  const Rect.fromLTWH(0, 0, 50, 20),
                                ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),

                // 控制按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    IconButton(
                      icon: ShaderMask(
                        shaderCallback:
                            (bounds) => themeGradient.createShader(bounds),
                        child: Icon(
                          Icons.replay_10,
                          color:
                              audioState.duration.inSeconds > 0
                                  ? Colors.white
                                  : Colors.grey,
                        ),
                      ),
                      iconSize: 36,
                      onPressed:
                          audioState.duration.inSeconds > 0
                              ? () {
                                // 确保不会跳到负值
                                int newPosition =
                                    audioState.position.inSeconds - 10;
                                if (newPosition < 0) newPosition = 0;

                                // 创建新位置对象
                                final targetPosition = Duration(
                                  seconds: newPosition,
                                );

                                // 检查是否跳转到已缓冲区域，回退通常是跳到已缓冲区域
                                final isBuffered = audioState
                                    .isPositionBuffered(targetPosition);
                                print(
                                  '回退10秒，目标位置: $targetPosition, 是否已缓冲: $isBuffered',
                                );

                                // 检查是否是大文件或FLAC格式
                                final isLargeFile =
                                    widget.fileSize != null &&
                                    widget.fileSize! > 20 * 1024 * 1024;
                                final isFlacFormat =
                                    widget.mimeType?.toLowerCase().contains(
                                          'flac',
                                        ) ==
                                        true ||
                                    widget.extension?.toLowerCase() == 'flac';
                                final needsSpecialHandling =
                                    isAndroid && (isLargeFile || isFlacFormat);

                                if (isBuffered && !needsSpecialHandling) {
                                  // 如果已缓冲且不需要特殊处理，直接跳转
                                  audioNotifier.seek(targetPosition);
                                } else {
                                  // 对于需要特殊处理的情况，使用更安全的跳转方式
                                  // 先暂停播放
                                  final wasPlaying = audioState.isPlaying;
                                  if (wasPlaying) {
                                    audioNotifier.pause();
                                  }

                                  // 给系统足够时间处理暂停操作
                                  Future.delayed(
                                    const Duration(milliseconds: 500),
                                    () {
                                      // 使用seek方法但增加安全措施
                                      audioNotifier.seek(targetPosition);

                                      // 如果之前是播放状态，恢复播放，但给予足够的缓冲时间
                                      if (wasPlaying) {
                                        Future.delayed(
                                          const Duration(milliseconds: 800),
                                          () {
                                            if (mounted) {
                                              audioNotifier.play();
                                            }
                                          },
                                        );
                                      }
                                    },
                                  );
                                }
                              }
                              : null,
                    ),
                    const SizedBox(width: 16),
                    IconButton(
                      icon: ShaderMask(
                        shaderCallback:
                            (bounds) => themeGradient.createShader(bounds),
                        child: Icon(
                          audioState.isPlaying
                              ? Icons.pause_circle_filled
                              : Icons.play_circle_filled,
                          color:
                              audioState.duration.inSeconds > 0
                                  ? Colors.white
                                  : Colors.grey,
                        ),
                      ),
                      iconSize: 56,
                      onPressed:
                          audioState.duration.inSeconds > 0
                              ? () {
                                if (audioState.isPlaying) {
                                  audioNotifier.pause();
                                } else {
                                  // 如果正在缓冲，给提示
                                  if (audioState.isBuffering) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: Text(
                                          '正在缓冲中，请稍候...',
                                          style: TextStyle(color: Colors.white),
                                        ),
                                        backgroundColor: _getLightThemeColor(
                                          context,
                                        ),
                                        duration: Duration(seconds: 2),
                                      ),
                                    );
                                    return;
                                  }
                                  audioNotifier.play();
                                }
                              }
                              : null,
                    ),
                    const SizedBox(width: 16),
                    IconButton(
                      icon: ShaderMask(
                        shaderCallback:
                            (bounds) => themeGradient.createShader(bounds),
                        child: Icon(
                          Icons.forward_10,
                          color:
                              audioState.duration.inSeconds > 0
                                  ? Colors.white
                                  : Colors.grey,
                        ),
                      ),
                      iconSize: 36,
                      onPressed:
                          audioState.duration.inSeconds > 0
                              ? () {
                                // 确保不会超过总时长
                                int newPosition =
                                    audioState.position.inSeconds + 10;
                                if (newPosition > audioState.duration.inSeconds)
                                  newPosition = audioState.duration.inSeconds;

                                // 创建新位置对象
                                final targetPosition = Duration(
                                  seconds: newPosition,
                                );

                                // 检查是否跳转到已缓冲区域
                                final isBuffered = audioState
                                    .isPositionBuffered(targetPosition);
                                print(
                                  '前进10秒，目标位置: $targetPosition, 是否已缓冲: $isBuffered',
                                );

                                // 检查是否是大文件或FLAC格式
                                final isLargeFile =
                                    widget.fileSize != null &&
                                    widget.fileSize! > 20 * 1024 * 1024;
                                final isFlacFormat =
                                    widget.mimeType?.toLowerCase().contains(
                                          'flac',
                                        ) ==
                                        true ||
                                    widget.extension?.toLowerCase() == 'flac';
                                final needsSpecialHandling =
                                    isAndroid && (isLargeFile || isFlacFormat);

                                if (isBuffered && !needsSpecialHandling) {
                                  // 如果已缓冲且不需要特殊处理，直接跳转
                                  audioNotifier.seek(targetPosition);
                                } else {
                                  // 对于需要特殊处理的情况，使用更安全的跳转方式
                                  // 先暂停播放
                                  final wasPlaying = audioState.isPlaying;
                                  if (wasPlaying) {
                                    audioNotifier.pause();
                                  }

                                  // 给系统足够时间处理暂停操作
                                  Future.delayed(
                                    const Duration(milliseconds: 500),
                                    () {
                                      // 使用seek方法但增加安全措施
                                      audioNotifier.seek(targetPosition);

                                      // 如果之前是播放状态，恢复播放，但给予足够的缓冲时间
                                      if (wasPlaying) {
                                        Future.delayed(
                                          const Duration(milliseconds: 800),
                                          () {
                                            if (mounted) {
                                              audioNotifier.play();
                                            }
                                          },
                                        );
                                      }
                                    },
                                  );
                                }
                              }
                              : null,
                    ),
                  ],
                ),
                const SizedBox(height: 32),

                // 下载按钮
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(24),
                    gradient: themeGradient,
                  ),
                  child: ElevatedButton.icon(
                    onPressed: () async {
                      if (widget.previewUrl != null) {
                        final url = Uri.parse(widget.previewUrl!);
                        if (await canLaunchUrl(url)) {
                          await launchUrl(
                            url,
                            mode: LaunchMode.externalApplication,
                          );
                        }
                      }
                    },
                    icon: const Icon(Icons.download, color: Colors.white),
                    label: const Text(
                      '下载音频文件',
                      style: TextStyle(color: Colors.white),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.transparent,
                      shadowColor: Colors.transparent,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 12,
                      ),
                    ),
                  ),
                ),
                // 底部添加空间
                const SizedBox(height: 20),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
